<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/5/7
 * Time: 21:14
 * Desc: 支付宝当面付
 */
namespace app\cash\controller;
use think\Controller;
use think\Db;
use think\Loader;
header('Content-type:text/html; Charset=utf-8');
Loader::import('alipay.pay.f2fpay.service.AlipayTradeService');
Loader::import('alipay.pay.aop.AopClient');
loader::import('alipay.pay.f2fpay.model.builder.AlipayTradePayContentBuilder');
class Alipay extends Controller{
    /**
     * @Author  lingyun
     * @Desc    支付宝支付
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    支付宝支付
     * 2018-05-06
     */
    public function pay(){
        $order_id = input('param.order_id');
        $auth_code = input('param.auth_code');
        if(empty($auth_code)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'订单创建失败，请重新创建'];
        }

        if(empty($order_id)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'msg'=>'订单创建失败，请重新创建'];
        }
        $order = db('order')->where('id',$order_id)->find();
        if(empty($order)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'msg'=>'订单创建失败，请重新创建'];
        }
        if($order['pay_status'] > 0){          //已经支付
            $this->error('该订单已经支付，请勿重复支付','');
//            return ['code'=>1,'msg'=>'支付成功'];
        }

        $root = request()->domain();                        //网站更目录

        $config = config('alipay');                         //支付宝配置信息
        $config['notify_url'] = $root.'/index.php/index/dangmianfu/alipay_notify';
//        $config['return_url'] = $root.'/index.php/index/dangmianfu/alipay_notify';
        $appid = $config['app_id'];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
//        $outTradeNo = $this->build_order_no($store_id);     //你自己的商品订单号
        $payAmount = $order['final_amount']-$order['pay_type_two'];          //付款金额，单位:元

        $orderName = '支付测试';    //订单标题
        $signType = 'RSA2';       //签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $body = '扫码支付';
        $subject = '支付宝支付';
//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        $saPrivateKey=$config['merchant_private_key'];


        $qrPayRequestBuilder = new \AlipayTradePayContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($order['order_sn']);
        $qrPayRequestBuilder->setTotalAmount($payAmount);
        $qrPayRequestBuilder->setAuthCode($auth_code);
        $qrPayRequestBuilder->setTimeExpress("5m");
        $qrPayRequestBuilder->setSubject($subject);
//        $qrPayRequestBuilder->setBody($body);

// 调用barPay方法获取当面付应答
        $qrPay = new \AlipayTradeService($config);
        $qrPayResult = $qrPay->barPay($qrPayRequestBuilder);

        $data = [];
        $data['status'] = $qrPayResult->getTradeStatus(); // SUCCESS/FAILED/UNKNOWN
        $response = json_decode(json_encode($qrPayResult->getResponse()), true);
//        file_put_contents('dangmianfu.txt',json_encode($qrPayResult->getResponse()));
        trace('alipay:' . json_encode($response), 'log');
        $data['message'] = $response['msg'];
        if ($data['status'] == 'SUCCESS') {
            $data['outer_sn'] = $response['out_trade_no'];
            $order = db('order')->where('order_sn',$data['outer_sn'])->find();
            $store = db('store')->where('id',$order['store_id'])->find();
            if($order['pay_status'] > 0){
                $this->success(2,'',$order['receipt']);
            }else{      //更新订单状态
                db('order')->where('order_sn',$data['outer_sn'])->update(['pay_status'=>1,'pay_time'=>time(),'pay_code'=>$response['trade_no'],'order_status'=>4]);

                if($order['coupon_id'] != ''){
                    db('user_ycard')->where(['coupon_id'=>$order['coupon_id'],'uid'=>$order['uid']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                }

                db('order_details')->where('order_id',$order['id'])->update(['status'=>4]);
                $order_action_arr = [
                    'uid'=>$order['uid'],
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>4,
                    'pay_status'=>1,
                    'status_desc'=>'订单已完成',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];

                db('order_action')->insert($order_action_arr);          //插入订单动作信息

                $pay_log_arr = [
                    'order_id'=>$order['id'],
                    'order_sn'=>$order['order_sn'],
                    'order_type'=>2,
                    'uid'=>$order['uid'],
                    'pay_type'=>$order['pay_type'],
                    'pay_sign'=>1,
                    'store_id'=>$order['store_id'],
                    'amount'=>$order['final_amount'],
                    'remark'=>'线下购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                    'addtime'=>time()
                ];

                db('pay_log')->insert($pay_log_arr);            //新增支付记录

                if(!empty($order['uid'])){
                    //变更积分
                    shouyintai_point($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],$money=0,$order['order_sn'],1);
                }
                $pay_type_two = (float)$order['pay_type_two'];
                $this->update_store_money($order['uid'],$store['id'],$order_id,$order['order_sn'],$pay_type_two,$order,$store);


                $casher = db('system_user')->where('id',$order['cashier'])->find();

                $order_details = db('order_details')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where('a.order_id',$order['id'])->field('a.id,a.goods_id,a.store_goods_stock_id,a.spec_detail,b.name,a.goods_num,a.final_amount,spec_price')->select();

                foreach($order_details as $k => $v){
                    $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                    $cur_stock = $stock['stock'] - $v['goods_num'];
                    //更新门店库存
                    db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                    $arr = [
                        'goods_id'=>$v['goods_id'],
                        'goods_spec_id'=>$stock['goods_spec_id'],
                        'title'=>$v['spec_detail'],
                        'order_id'=>$order['id'],
                        'store_id'=>$order['store_id'],
                        'types'=>2,
                        'ruku_num'=>0,
                        'tuihuo_num'=>0,
                        'chuku_num'=>$v['goods_num'],
                        'sunhao_num'=>0,
                        'remark'=>$order['order_sn'],
                        'cur_stock'=>$cur_stock,
                        'addtime'=>time(),
                        'order_sn'=>$order['order_sn']
                    ];
                    db('store_goods_log')->insert($arr);
                }

                $this->success(2,'',$order['receipt']);
            }
        } else {
            $data['message'] .= $response['sub_msg'];
            $this->error($data['message']);
        }
    }

    /**
     * @Author  lingyun
     * @Desc    更新门店余额
     */
    private function update_store_money($uid=0,$store_id,$order_id,$sn,$pay_type_two=0,$order,$store){
        if(empty($uid)){
            $member = db('user')->where('uid',$uid)->find();
            if(!empty($pay_type_two)){
                $data_wallet_arr = [
                    'uid' => $uid,
                    'admin_id' => 0,
                    'store_id' => $store_id,
                    'order_id' => $order_id,
                    'order_sn' => $sn,
                    'pay_time' => time(),
                    'pay_status' => 1,
                    'pay_type' => 3,
                    'amount' => $pay_type_two,
                    'cur_amount' => $member['user_money'] - $pay_type_two,
                    'sign' => 2,
                    'chargetype' => 1,
                    'charge_cn' => '支付订单',
                    'addtime' => time()
                ];
                //记录余额记录
                db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                db('user')->where('uid', $uid)->setDec('user_money', $pay_type_two);
            }
        }
        $log_money = $order['final_amount'] - $pay_type_two;
        $store_credit_log = [
            'store_id' => $store_id,
            'order_id' => $order_id,
            'type' => 1,
            'credit' => $log_money,
            'cur_credit' => $store['total_amount'] + $log_money,
            'remark' => '销售商品收入',
            'addtime' => time(),
            'order_type' => 1,
            'order_sn' => $sn,
            'pay_type' => 1
        ];
        db('store_credit_log')->insert($store_credit_log);
        $store_credit_arr['total_amount'] = $store['total_amount'] + $log_money;
        $store_credit_arr['al_money'] = $store['al_money'] + $log_money;
        db('store')->where('id', $store_id)->update($store_credit_arr);

        if(!empty($pay_type_two)){
            $store_credit_log1 = [
                'store_id' => $store_id,
                'order_id' => $order_id,
                'type' => 1,
                'credit' => $pay_type_two,
                'cur_credit' => $store['total_amount'] + $log_money + $pay_type_two,
                'remark' => '销售商品收入',
                'addtime' => time(),
                'order_type' => 1,
                'order_sn' => $sn,
                'pay_type' => 3
            ];
            db('store_credit_log')->insert($store_credit_log1);
            $store_credit_arr1['total_amount'] = $store['total_amount'] + $log_money + $pay_type_two;
            $store_credit_arr1['credit'] = $store['credit'] + $pay_type_two;
            $store_credit_arr1['user_money'] = $store['user_money'] + $pay_type_two;
            db('store')->where('id', $store_id)->update($store_credit_arr1);
        }
    }

    /**
     * @Author  lingyun
     * @Desc    生成订单
     * @return string
     */
    private function build_order_no($store_id){
        return date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$store_id;
    }

    /**
     * @Author  lingyun
     * @Desc    会员充值
     * 2018-06-11
     */
    public function recharge(){
        $order_id = input('param.order_id');
        $auth_code = input('param.auth_code');
        if(empty($auth_code)){
            $this->error('订单创建失败，请重新创建');
        }

        if(empty($order_id)){
            $this->error('订单创建失败，请重新创建');
        }
        $order = db('user_wallet_log')->where('id',$order_id)->find();
        if(empty($order)){
            $this->error('订单创建失败，请重新创建');
        }
        if($order['pay_status'] == 1){          //已经支付
            $this->success(2,'');
        }

        $root = request()->domain();                        //网站更目录

        $config = config('alipay');                         //支付宝配置信息
        $config['notify_url'] = $root.'/index.php/index/dangmianfu/alipay_notify';
//        $config['return_url'] = $root.'/index.php/index/dangmianfu/alipay_notify';
        $appid = $config['app_id'];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
//        $outTradeNo = $this->build_order_no($store_id);     //你自己的商品订单号
        $payAmount = $order['amount'];          //付款金额，单位:元

        $orderName = '支付测试';    //订单标题
        $signType = 'RSA2';       //签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $body = '扫码支付';
        $subject = '支付宝支付';
//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        $saPrivateKey=$config['merchant_private_key'];


        $qrPayRequestBuilder = new \AlipayTradePayContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($order['order_sn']);
        $qrPayRequestBuilder->setTotalAmount($payAmount);
        $qrPayRequestBuilder->setAuthCode($auth_code);
        $qrPayRequestBuilder->setTimeExpress("5m");
        $qrPayRequestBuilder->setSubject($subject);
//        $qrPayRequestBuilder->setBody($body);

// 调用barPay方法获取当面付应答
        $qrPay = new \AlipayTradeService($config);
        $qrPayResult = $qrPay->barPay($qrPayRequestBuilder);

        $data = [];
        $data['status'] = $qrPayResult->getTradeStatus(); // SUCCESS/FAILED/UNKNOWN
        $response = json_decode(json_encode($qrPayResult->getResponse()), true);
        trace('alipay:' . json_encode($response), 'log');
        $data['message'] = $response['msg'];
        if ($data['status'] == 'SUCCESS') {
            $data['outer_sn'] = $response['out_trade_no'];
            $order = db('user_wallet_log')->where('order_sn',$data['outer_sn'])->find();
            if($order['pay_status'] == 1){
                $this->success('支付成功','');
            }else{      //更新订单状态
                //会员信息
                $member = Db::name('user')->where('uid',$order['uid'])->find();
                $cur_amount = $member['user_money']+$order['amount'];        //会员当前余额

                //变更会员余额
                Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$order['amount']);
                //更新订单状态
                Db::name('user_wallet_log')->where('order_sn',$order['order_sn'])->update(['pay_code'=>$order['order_sn'],'pay_time'=>time(),'pay_status'=>1,'pay_type'=>1,'amount'=>$order['amount'],'cur_amount'=>$cur_amount,'sign'=>2,'chargetype'=>2,'charge_cn'=>'余额充值']);
                //记录支付日志
                Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>1,'pay_sign'=>2,'amount'=>$order['amount'],'addtime'=>time(),'remark'=>'会员充值，订单号'.$order['order_sn'].'，充值金额：'.$order['amount'],'store_id'=>$order['store_id']]);


                $store = db('store')->where('id',$order['store_id'])->find();

                $receipt = '';          //线下小票信息
                $receipt .= '<tr><td colspan="4" style="font-size: large;text-align: center">'.$store["title"].'</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号：'.$order["order_sn"].'</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员：' . session("cash_user")["realname"] . '</td></tr><tr><td colspan="4" style="text-align: center">—————————————————</td></tr>';

                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">充值金额：'.$order["amount"].'</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';

                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">姓名：' . $member["realname"] . '     手机：' . $member["mobile"] . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">会员卡：' . $member["pay_code"] . '     余额：￥' . $cur_amount . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';

                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">付款方式：支付宝 </td></tr>';

                $receipt .= '<tr><td colspan="4" style="text-align: left;font-size: smaller;">' . $store["address"] . '</td></tr>';
                $receipt .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
                $receipt .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';

                //门店会员充值金额
                $store_credit_log = [
                    'recharge_amount'=>$store['recharge_amount']+$order['amount']
                ];
                db('store')->where('id',$store['id'])->update($store_credit_log);       //记录门店充值记录

                //会员充值三级分销变更记录
                recharge_third_distribution($order['uid'],$order['amount']);

//                if(!empty($member['openid'])){
//                    $root = request()->domain();
//                    //推送模板消息
//                    $array = [
//                        "type"   	  =>1,
//                        "touser" 	  =>$member["openid"],
//                        "template_id"=>config("weixin_mu_msg.recharge_msg")["tempid"],
//                        "url" 		  =>$root.'/index.php/index/user/recharge',
//                        "topcolor"  =>"#743A3A",
//                        "data"   =>[
//                            "first" 	    =>["value"=>'充值成功提醒', "color"=>"#743A3A"],
//                            "accountType" 	    =>["value"=>'充值时间', "color"=>"#743A3A"],
//                            "account"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
//                            "amount"		=>["value"=>$result['total_amount'], 		"color"=>"#743A3A"],
//                            "result"		=>["value"=>'充值成功',"color"=>"#743A3A"],
//                            "remark"		=>["value"=>"您已成功充值，请注意卡内余额变动", 			"color"=>"#743A3A"],
//                        ]
//                    ];
//                    $this->sendMessage($array);
//                }
                $this->success('支付成功','',$receipt);
            }
        } else {
            $data['message'] .= $response['sub_msg'];
            $this->error($data['message']);
        }
    }


}
